//
//  CWQ_userInfoVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/9/9.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "CWQ_userLevelVC.h"
#import "CWQ_userInfoHeadView.h"

static CGFloat topContentInset = 166;

@interface CWQ_userLevelVC ()<UIScrollViewDelegate, CWQ_userInfoHeadViewDelegate, UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
//<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) UIView *navBarView;
@property (nonatomic, strong) UIView *navBarBgView;
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_8_0

@property (nonatomic, strong) WKWebView *webView;
#else
@property (nonatomic, strong) UIWebView *webView;
#endif

@property (nonatomic, strong) CWQ_userInfoHeadView *headView;
@property (nonatomic, strong) UIImageView *headbgView;
@property (nonatomic, strong) BTUserLevelM *userLevelM;
@end

@implementation CWQ_userLevelVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.webView];
    weakSelf_define;
    

    NSString *url = [NSString stringWithFormat:@"%@/%@",[BTNetworkManager sharedMg].bathURL,kBaxterMember];
    [HELAppManager jSessionIdOverTime:^(NSString *sessionID) {
        NSMutableURLRequest *reques = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [reques  addValue:sessionID forHTTPHeaderField:@"x-auth-token"];

        weakSelf.webView.UIDelegate = self;
        [weakSelf.webView loadRequest:reques];
        
    } sessionFailure:^{
        
    }];
    [self createNavBar];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createHeadView];
    [self requestUserLevelData];
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}
#pragma mark - Getters
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
- (WKWebView *)webView {
    if (_webView) return _webView;
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    _webView.scrollView.delegate = self;
    return _webView;
}

#else
- (UIWebView *)webView {
    if (_webView) return _webView;
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    _webView.translatesAutoresizingMaskIntoConstraints = NO;
    return _webView;
}
#endif

#pragma mark - 创建tableView
- (void)createNavBar {
    
    _navBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64)];
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"back copy"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 10)];
    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setBounds:CGRectMake(0, 0, kScreenWidth - 44*2, 44)];
    titleLabel.center = CGPointMake(kScreenWidth/2, 42);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"我的积分";
    _navBarView.backgroundColor = kMainColor;
    [_navBarView setAlpha:0];
    _navBarBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64)];
    //    _navBarBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_navBarView];
    [self.view addSubview:_navBarBgView];
    [_navBarBgView addSubview:backBtn];
    [_navBarBgView addSubview:titleLabel];
    
}
- (void)dealloc {

    self.webView.scrollView.delegate = nil;
    self.webView = nil;

}
#pragma mark - 创建头像视图
- (void)createHeadView
{
    CWQ_userInfoHeadView *headView = [CWQ_userInfoHeadView headView];
    headView.delegate = self;
   
    [headView setFrame:CGRectMake(0, -cwqGetCustomHeight(topContentInset), kScreenWidth, cwqGetCustomHeight(topContentInset))];
    headView.backgroundColor = [UIColor clearColor];
    UIImageView *headbgView = [[UIImageView alloc] initWithFrame:headView.bounds];
    headbgView.contentMode = UIViewContentModeScaleAspectFill;
    // 这个属性决定了子视图的显示范围 取值为YES时，剪裁超出父视图范围的子视图部分.这里就是裁剪了_pictureImageView超出_header范围的部分.
    headbgView.clipsToBounds = YES;
    [headbgView setImage:[UIImage imageNamed:@"背景"]];
    [headView insertSubview:headbgView atIndex:0];
//    [_webView.scrollView addSubview:headbgView];
    [_webView.scrollView addSubview:headView];
    _webView.scrollView.contentInset = UIEdgeInsetsMake(cwqGetCustomHeight(topContentInset), 0, 0, 0);
    
    _headbgView = headbgView;
    
    _headView = headView;
}


- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.navBarView.alpha = 0;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self cleanCacheAndCookie];
}


- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma -mark----获取数据---------
- (void)requestUserLevelData {
    weakSelf_define;
    cwqHud;
    [[BTNetworkManager sharedMg] POST:BTUserScoreLevelUrl parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
            BTUserLevelM *userLevelM = [BTUserLevelM mj_objectWithKeyValues:responseObject[@"data"]];
            [weakSelf.headView setModel:userLevelM];
        }
    } failure:^(NSString *err) {
        
    }];
    
}



#pragma -mark------上传头像到图片服务器---------
- (void)uploadHeadPhoto:(UIImage *)image{
    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.headView animated:YES];
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    hud.animationType = MBProgressHUDModeAnnularDeterminate;
    hud.detailsLabelText = @"正在上传...";
    hud.progress = 0;
    [hud show:YES];

    weakSelf_define;
    [[BTNetworkManager sharedMg] UPLOAD:BTUpLoadUrl parameters:@{@"app":@"public"} image:image progress:^(CGFloat percent) {
        hud.progress = percent;
    } success:^(id responseObject) {
        [hud hide:YES afterDelay:.4];
        [weakSelf uploadImageUrl:responseObject[@"thumbUrl"]];
    } failure:^(NSString *err) {
         [hud hide:YES afterDelay:.4];
    }];
}


#pragma -mark------上传头像链接---------
- (void)uploadImageUrl:(NSString *)imageUrl{
    
    
    [[BTNetworkManager sharedMg] POST:BTUpLoadHeadImageUrl parameters:@{@"headImgUrl":imageUrl} success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            cwqAlertMessage(@"修改头像成功");
        }
    } failure:^(NSString *err) {
        
    }];
}


#pragma mark--headview代理
- (void)headView:(CWQ_userInfoHeadView *)headView clickHeadBtn:(UIButton *)headBtn {
    UIActionSheet *actionSheetView = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册" ,nil];
    [actionSheetView showInView:self.navigationController.view];
}

- (void)headView:(CWQ_userInfoHeadView *)headView clickIntegralBtn:(UIButton *)integralBtn {


}

- (void)headView:(CWQ_userInfoHeadView *)headView clickTrainCampBtn:(UIButton *)trainCampBt {



}

#pragma mark -------------headPhotoClick--------------------


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else if(buttonIndex == 1){
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }
    
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    [self.headView.headBtn setImage:img forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self uploadHeadPhoto:img];
}


#pragma mark - 滑动代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y + self.webView.scrollView.contentInset.top;//注意
    CGFloat topEdge = CGRectGetMinY(self.headView.headBtn.frame)-64;
    if (topEdge > 0) {
        if (offsetY <= CGRectGetMinY(self.headView.headBtn.frame)-64) {
            
            if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
                [self setNeedsStatusBarAppearanceUpdate];
            }
            [self.navBarView setAlpha:0];
        }
        else if (offsetY > CGRectGetMinY(self.headView.headBtn.frame)-64) {
            
            [self.navBarView setAlpha:1];
        }
    }
    
    
    if ( offsetY < 0) {
        // 拉伸后图片的高度
        CGFloat totalOffset = cwqGetCustomHeight(topContentInset) - offsetY;
        // 图片放大比例
        CGFloat scale = totalOffset / cwqGetCustomHeight(topContentInset);
        CGFloat width = kScreenWidth;
        // 拉伸后图片位置
        _headbgView.frame = CGRectMake(-(width * scale - width) / 2, offsetY, width * scale, totalOffset);
    }

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
